package com.demo;

import com.demo.nio.NioOp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @author jasper
 */
@SpringBootApplication
@Slf4j
public class DemoApplication implements CommandLineRunner {
    int count = 0;

    @Autowired
    private NioOp nioOp;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @SuppressWarnings("AlibabaAvoidManuallyCreateThread")
    @Override
    public void run(String... args) throws Exception {
    }

    /**
     * 脚本执行 String command = Gather.DATAX_SHELL_PATH;
     *
     * @param args    参数
     * @param command 脚本
     * @return 执行返回的状态
     */
    public int exec(String args, String command) {
        int status = -1;
        log.info("exec command " + command);
        log.info("args: " + args);
        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec(command + " " + args);
            InputStream errorStream = process.getErrorStream();
            BufferedReader errorBufferedReader = new BufferedReader(new InputStreamReader(errorStream,
                    StandardCharsets.UTF_8));
            StringBuilder errorSb = new StringBuilder();
            InputStream inputStream = process.getInputStream();
            BufferedReader inputBufferedReader = new BufferedReader(new InputStreamReader(inputStream,
                    StandardCharsets.UTF_8));
            StringBuilder inputSb = new StringBuilder();
            readProcessStream(inputSb, inputBufferedReader);
            readProcessStream(errorSb, errorBufferedReader);
            status = process.exitValue();
            log.info("exec shell log: \n" + errorSb.toString());
        } catch (IOException e) {
            log.error("exec command: " + command + " error!", e);
        }
        return status;
    }

    private void readProcessStream(StringBuilder sb, BufferedReader bufferedReader) {
        String line;
        try {
            Thread.sleep(100);
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } catch (Exception e) {
            log.error("read buffer to sb error: ", e);
        }
        log.info("read buffer to sb success");
    }
}
